package com.novax.ex.activity.provider.controller.inner;

import com.novax.ex.activity.infrastructure.entity.TaskLanguage;
import com.novax.ex.activity.infrastructure.entity.TaskRule;
import com.novax.ex.activity.open.api.inner.TaskRuleApi;
import com.novax.ex.activity.open.model.request.task.TaskRuleRequest;
import com.novax.ex.activity.open.model.response.task.TaskRuleResponse;
import com.novax.ex.activity.provider.controller.BaseActivityController;
import com.novax.ex.activity.provider.service.TaskRuleService;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.CopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 后管 规则配置
 * @Author ChenXi
 * @Date 2023/06/21/10:34
 */

@RestController
public class TaskRuleController extends BaseActivityController implements TaskRuleApi {

    @Resource
    private TaskRuleService taskRuleService;

    @Override
    public ReturnResult<List<TaskRuleResponse>> queryAll() {
        return ReturnResult.success(CopyUtils.copyList(taskRuleService.queryAll(), TaskRuleResponse.class));
    }

    @Override
    public ReturnResult<?> modify(String language, Long id, TaskRuleRequest taskRuleRequest) {
        // 语言不可更改
        taskRuleRequest.setLanguage(null);
        TaskRule taskRule = CopyUtils.copyObject(taskRuleRequest, TaskRule.class);
        taskRule.setId(id);
        boolean flag = taskRuleService.modifySelective(taskRule);
        return flag ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

    @Override
    public ReturnResult<?> add(String language, TaskRuleRequest taskRuleRequest, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ReturnResult.fail(getInternational(language, InternationalCode.LACK_VALUE));
        }

        Map<String, Object> query = new HashMap<>(2);
        query.put("language", taskRuleRequest.getLanguage());
        List<TaskLanguage> list = taskRuleService.findList(query);

        // 新增时判断语言是否已配置
        if(!list.isEmpty()){
            return ReturnResult.fail(getInternational(language, InternationalCode.LANGUAGE_EXIST));
        }

        TaskRule taskRule = CopyUtils.copyObject(taskRuleRequest, TaskRule.class);
        boolean flag = taskRuleService.addSelective(taskRule);;
        return flag ? ReturnResult.success(getInternational(language, InternationalCode.OPERATION_SUCCESS))
            : ReturnResult.fail(getInternational(language, InternationalCode.OPERATION_ERROR));
    }

}
